package com.zh.web.controllers;

import com.zh.utils.SnowflakeIdGenerator;
import com.zh.web.bean.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/id")
public class IdController {

    @Autowired
    private SnowflakeIdGenerator generator;

    @GetMapping("/next")
    public ResponseResult getNextId() {
        return ResponseResult.builder().code(1).data( generator.nextId() ).build();
    }

    /**
     * 批量 ID
     */
    @GetMapping("/batch")
    public ResponseResult getBatchIds(@RequestParam(value="size", defaultValue = "10") int size) {
        List<Long> ids = generator.nextIdBatch(size);
        return ResponseResult.builder()
                .code(1)
                .data(ids)
                .build();
    }

    /**
     * 解析时间戳
     */
    @GetMapping("/parse/time")
    public ResponseResult parseTime(@RequestParam("id") long id) {
        long ts = generator.parseIdToTime(id);
        return ResponseResult.builder()
                .code(1)
                .data(new TimeResult(ts, new Date(ts)))
                .build();
    }

    /**
     * 解析 datacenterId
     */
    @GetMapping("/parse/datacenter")
    public ResponseResult parseDatacenter(@RequestParam("id") long id) {
        return ResponseResult.builder()
                .code(1)
                .data(generator.parseIdToDatacenterId(id))
                .build();
    }

    /**
     * 解析 workerId
     */
    @GetMapping("/parse/worker")
    public ResponseResult parseWorker(@RequestParam("id") long id) {
        return ResponseResult.builder()
                .code(1)
                .data(generator.parseIdToWorkerId(id))
                .build();
    }

    /**
     * 内部时间封装类
     */
    @lombok.Data
    @lombok.AllArgsConstructor
    static class TimeResult {
        private long timestamp;
        private Date date;
    }




}

